const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
require('dotenv').config();
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/users');
const resourceRoutes = require('./routes/resources');
const challengeRoutes = require('./routes/challenges');
const businessRoutes = require('./routes/business');

const app = express();

// CORS 配置
app.use(cors({
  origin: 'http://localhost:3000', // 前端应用的地址
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

app.use(express.json());

// 调试日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next();
});

// 静态文件服务
app.use('/images', express.static(path.join(__dirname, 'public/images')));

// 连接数据库
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/green_planet')
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.error('MongoDB connection error:', err));

// API 路由配置
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/resources', resourceRoutes);
app.use('/api/challenges', challengeRoutes);
app.use('/api/business', businessRoutes);

// API 路由错误处理
app.use('/api', (err, req, res, next) => {
  console.error('API错误:', err.stack);
  res.status(500).json({ message: '服务器错误' });
});

// API 404处理
app.use('/api', (req, res) => {
  console.log(`API 404 - Not Found: ${req.method} ${req.url}`);
  res.status(404).json({ message: '未找到请求的资源' });
});

// 其他所有请求返回index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../client/build/index.html'));
});

const PORT = process.env.PORT || 5001;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`API available at http://localhost:${PORT}/api`);
});

module.exports = app; 